package com.gx.smart.construction.ui.login.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.casic.gx.grpc.common.ComResp;
import com.gx.smart.base.BaseViewModel;
import com.gx.smart.common.util.AppConfig;
import com.gx.smart.lib.event.LoadingMessageEvent;
import com.gx.smart.lib.http.api.AuthApiService;
import com.gx.smart.lib.http.api.ConstructionAppConstructionAppUserProviderService;
import com.gx.smart.lib.http.api.asynctask.CallBack;
import com.gx.wisestone.constructionappgrpclib.grpc.constructionappuser.ConstructionAppConstructionAppLoginResponse;
import com.gx.wisestone.constructionappgrpclib.grpc.constructionappuser.ConstructionAppConstructionAppUserDto;
import com.gx.wisestone.uaa.grpc.lib.auth.LoginResp;
import com.gx.wisestone.uaa.grpc.lib.auth.VerifyCodeResp;

import org.greenrobot.eventbus.EventBus;


public class LoginViewModel extends BaseViewModel {
    private MutableLiveData<Boolean> loginSuccess = new MutableLiveData<>();
    private MutableLiveData<Boolean> verifyCodeSuccess = new MutableLiveData<>();
    public final ObservableField<String> phoneNumber = new ObservableField<>();
    public final ObservableField<String> phonePassword = new ObservableField<>();
    public final ObservableInt tabIndex = new ObservableInt(0);
    public final ObservableBoolean verifyCodeEnable = new ObservableBoolean(true);
    private MutableLiveData<Boolean> loginEnable = new MutableLiveData(true);

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<Boolean> getLoginEnable(){
        return this.loginEnable;
    }

    //登录类型 1 账号; 2 手机号; 3 短信验证码
    //登录UAA
    public LiveData<Boolean> login(String phone, String password, int loginType) {
        loginEnable.setValue(false);
        EventBus.getDefault().post(new LoadingMessageEvent(true));
        AuthApiService.getInstance().login(phone, password, loginType, new CallBack<LoginResp>() {

            @Override
            public void callBack(LoginResp result) {
                EventBus.getDefault().post(new LoadingMessageEvent(false));
                loginEnable.setValue(true);
                if (result == null) {
                    loginSuccess.setValue(false);
                    ToastUtils.showLong("服务器超时");
                    return;
                }
                if (result.getCode() == 100) {
                    if (loginType == 2) {
                        saveLogin(phone, password, result.getToken());
                    } else {
                        saveLogin(phone, "", result.getToken());
                    }
                    loginApp(phone);
                } else {
                    loginSuccess.setValue(false);
                    ToastUtils.showLong(result.getMsg());
                }

            }
        });
        return loginSuccess;
    }

    //登录系统获取用户相关信息
    public void loginApp(String phone) {
        ConstructionAppConstructionAppUserProviderService.getInstance().login(phone,
                new CallBack<ConstructionAppConstructionAppLoginResponse>() {

            @Override
            public void callBack(ConstructionAppConstructionAppLoginResponse result) {
                if (result == null) {
                    loginSuccess.setValue(false);
                    ToastUtils.showLong("服务器超时");
                    return;
                }
                ComResp comResp = result.getComResp();
                if (comResp.getCode() == 100) {
                    ToastUtils.showLong("登录成功");
                    ConstructionAppConstructionAppUserDto data = result.getDto();
                    saveAppLogin(data.getId(), data.getName(), data.getTenantIds());
                    loginSuccess.setValue(true);
                } else {
                    loginSuccess.setValue(false);
                    handleServiceException(comResp);
                }
            }
        });
    }


    /**
     * //获取登录验证码
     * int targetType = 1;
     * int purpose = 1;
     */
    public LiveData<Boolean> getVerifyCode(String phone) {
        //获取登录验证码
        int targetType = 1;
        int purpose = 1;
        AuthApiService.getInstance().verifyCode(phone, targetType, purpose,
                new CallBack<VerifyCodeResp>() {

            @Override
            public void callBack(VerifyCodeResp result) {
                if (result == null) {
                    verifyCodeSuccess.setValue(false);
                    ToastUtils.showLong("服务器超时");
                    return;
                }

                if (result.getCode() == 100) {
                    ToastUtils.showLong("获取验证码成功");
                    verifyCodeSuccess.setValue(true);
                } else {
                    verifyCodeSuccess.setValue(false);
                    ToastUtils.showLong(result.getMsg());
                }
            }
        });
        return verifyCodeSuccess;
    }


    /**
     * string name = 3;  //用户姓名
     * string mobile = 4;  //手机号码
     * string user_id = 5;  //用户池ID
     * string tenant_ids = 6;  //小区id用逗号隔开
     *
     * @param phone
     * @param password
     * @param token
     */
    private void saveLogin(String phone, String password, String token) {
        SPUtils.getInstance().put(AppConfig.LOGIN_ACCOUNT, phone);
        SPUtils.getInstance().put(AppConfig.LOGIN_PASSWORD, password);
        SPUtils.getInstance().put(AppConfig.LOGIN_TOKEN, token);
    }


    private void saveAppLogin(String id, String userName, String tenant_ids) {
        SPUtils.getInstance().put(AppConfig.USER_ID, id);
        SPUtils.getInstance().put(AppConfig.USER_NAME, userName);
        SPUtils.getInstance().put(AppConfig.USER_TENANT_IDS, tenant_ids);
    }

}
